package cn.hjh.rpc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import cn.hjh.rpc.define.RPCClientBean;
import cn.hjh.rpc.define.ReplyMode;

public class RPCManager
{

	private static RPCManager instance;
	
	private static final Lock lock = new ReentrantLock();
	
	private static final String TEMP_TEMPLATE = "tempAmqpTemplate";
	
	private static final String REPLY_TO = "replyTo";
	
	private RPCManager(){}
	
	/** 单例模式*/
	public static RPCManager getInstance()
	{
		if(null == instance)
		{
			lock.lock();
			try
			{
				if(null == instance)
				{
					instance = new RPCManager();
				}
			} 
			catch (Exception e)
			{
				e.printStackTrace();
			}
			finally
			{
				lock.unlock();
			}
		}
		return instance;
	}
	
	public Object send(String beanId, Object obj)
	{
		RPCClientBean bean = SpringContextUtil.getApplicationContext().getBean(beanId, RPCClientBean.class);
		MessageProperties msgProp = new MessageProperties();
		msgProp.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);
		msgProp.setHeader(REPLY_TO, bean.getReplyQueueKey());
		
		//TODO
		Message msg = new Message(((String)obj).getBytes(),msgProp);
		
		return send(beanId, msg);
	}
	
	public Object send(String beanId, Message message)
	{
		if(StringUtils.isEmpty(beanId))
		{
			throw new RuntimeException("beanId 不能为空");
		}
		
		RPCClientBean bean = SpringContextUtil.getApplicationContext().getBean(beanId, RPCClientBean.class);
		
		RabbitTemplate rabbitTemplate = null;
		if(ReplyMode.FIX.name().equals(bean.getReplyMode().name()))
		{
			rabbitTemplate = SpringContextUtil.getApplicationContext().getBean(bean.getSendQueueName(), RabbitTemplate.class);
		}
		else
		{
			rabbitTemplate = SpringContextUtil.getApplicationContext().getBean(TEMP_TEMPLATE, RabbitTemplate.class);
		}
		
		return rabbitTemplate.convertSendAndReceive(bean.getSendQueueKey(), message);
	}
}
